﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using TicketManager.Data;
using TicketManager.Entities;
using System.Data.SqlClient;

public partial class BookingTickets : System.Web.UI.Page
{
    int ra;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDdlRap();
            BindDdlPhim();
            BindDdlLoaiVe();
        }
    }

    #region Bind data to DropDownList - Rap
    protected void BindDdlRap()
    {
        DataTable dt = DataRepository.RapProvider.GetAll().ToDataSet(false).Tables[0];
        if (dt != null)
        {
            ddlRap.DataSource = dt;
            ddlRap.DataTextField = RapColumn.TenRap.ToString();
            ddlRap.DataValueField = RapColumn.RapId.ToString();
            ddlRap.DataBind();
            ddlRap.Items.Insert(0, "------Chọn rạp------");
        }
    }
    #endregion

    #region Bind data to DropDownList - Phim
    protected void BindDdlPhim()
    {
        //DataTable dt = DataRepository.PhimProvider.GetAll().ToDataSet(false).Tables[0];
        PhimFilters pfiter = new PhimFilters();
        pfiter.Append(PhimColumn.TrangThai, "true");
        DataTable dt = DataRepository.PhimProvider.GetPaged(pfiter.ToString(), PhimColumn.TenPhim.ToString() + " ASC", 0, int.MaxValue, out ra).ToDataSet(false).Tables[0];

        if (dt != null)
        {
            ddlPhim.DataSource = dt;
            ddlPhim.DataTextField = PhimColumn.TenPhim.ToString();
            ddlPhim.DataValueField = PhimColumn.PhimId.ToString();
            ddlPhim.DataBind();
            ddlPhim.Items.Insert(0, "-----Chọn phim-----");
        }
    }
    #endregion

    #region Bind data to DropDownList - Loại vé
    protected void BindDdlLoaiVe()
    {
        LoaiveFilters pfiter = new LoaiveFilters();        
        DataTable dt = DataRepository.LoaiveProvider.GetPaged(pfiter.ToString(), LoaiveColumn.TenVe.ToString() + " ASC", 0, int.MaxValue, out ra).ToDataSet(false).Tables[0];

        if (dt != null)
        {
            ddlLoaiVe.DataSource = dt;
            ddlLoaiVe.DataTextField = LoaiveColumn.TenVe.ToString();
            ddlLoaiVe.DataValueField = LoaiveColumn.LoaiVeId.ToString();
            ddlLoaiVe.DataBind();
            ddlLoaiVe.Items.Insert(0, "-----Chọn loại vé-----");
        }
    }
    #endregion

    #region InsertUser
    protected int InsertUser(string userId)
    {
        User user;
        if (string.IsNullOrEmpty(userId))
        {
            user = new User();
        }
        else
        {
            user = DataRepository.UserProvider.GetByUserId(Convert.ToInt32(userId));
        }
        user.TenDangNhap = txtUserName.Text;
        user.TenHienThi = txtName.Text;
        user.MatKhau = txtPass.Text;
        user.Email = txtEmail.Text;
        user.DiaChi = txtDiaChi.Text;
        user.SoCmtnd = txtCMT.Text;
        user.SoDienThoai = txtPhone.Text;
        if (string.IsNullOrEmpty(userId))
            DataRepository.UserProvider.Insert(user);
        else
            DataRepository.UserProvider.Update(user);
        return user.UserId;
    }
    #endregion

    #region Insert Ticket
    protected int InsertTicket()
    {
        Ve ve = new Ve();
        ve.LoaiVeId = Convert.ToInt32(ddlLoaiVe.SelectedValue);
        ve.PhimId = Convert.ToInt32(ddlPhim.SelectedValue);
        ve.GheId = 1;
        ve.PhongId = 1;
        ve.RapId = Convert.ToInt32(ddlRap.SelectedValue);
        ve.TenVe = ddlPhim.SelectedItem.Text;
        DataRepository.VeProvider.Insert(ve);
        return ve.VeId;
    }
    #endregion

    #region Get So lan dat
    protected int GetSoLanDat(int userId)
    {
        LichSuGdkhFilters filter = new LichSuGdkhFilters();
        filter.AppendEquals(LichSuGdkhColumn.UserId, userId.ToString());
        DataTable dt = DataRepository.LichSuGdkhProvider.GetPaged(filter.ToString(), "", 0, int.MaxValue, out ra).ToDataSet(false).Tables[0];
        if (dt != null)
            return dt.Rows.Count;
        else
            return 0;
    }
    #endregion

    #region Insert history
    protected void InsertHistory(int userId,int veId)
    {
        LichSuGdkh gd = new LichSuGdkh();
        gd.UserId = userId;
        gd.VeId = veId;
        gd.NgayDatVe = DateTime.Now;
        gd.SoLanDat = GetSoLanDat(userId) + 1;
        DataRepository.LichSuGdkhProvider.Insert(gd);
    }
    
    #endregion

    #region btnSend_Click
    protected void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
            int userId=0;
            //insert user if not exist            
            if (!CheckUserExist(txtUserName.Text))
            {
                if (hddCheckUser.Value == "1")
                {
                    //Đăng nhập
                    userId = InsertUser(string.Empty);
                }
                else
                {
                    //Đăng ký
                    Response.Write("<script>alert('Tên đăng nhập không tồn tại. Vui lòng chọn đăng ký.')</script>");
                    return;
                }
            }//Đăng ký
            else
            {                
                if (hddCheckUser.Value == "0")
                {
                    if (!CheckUserExist(txtUserName.Text, txtPass.Text))
                    {
                        Response.Write("<script>alert('Sai tên đăng nhập hoặc mật khẩu')</script>");
                        return;
                    }
                    userId = GetUserIdByUserName(txtUserName.Text);
                    if (userId == 0)
                    {
                        Response.Write("<script>alert('Tên đăng nhập đã tồn tại. Vui lòng chọn tên đăng nhập khác.')</script>");
                        return;
                    }
                }                
            }
            //insert ticket
            int veId = InsertTicket();
            //insert history
            InsertHistory(userId, veId);
            Response.Write("<script>alert('Đăng ký thành công')</script>");
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    #endregion

    #region CheckUserExist
    protected bool CheckUserExist(string userName)
    {
        UserFilters uFilter = new UserFilters();
        uFilter.AppendEquals(UserColumn.TenDangNhap, userName);        
        DataTable dt = DataRepository.UserProvider.GetPaged(uFilter.ToString(), "", 0, int.MaxValue, out ra).ToDataSet(false).Tables[0];
        if (dt!=null)
        {
            if (dt.Rows.Count>0)
            {
                return true;
            }
        }
        return false;
    }
    #endregion

    #region CheckUserExist
    protected bool CheckUserExist(string userName,string passWord)
    {
        UserFilters uFilter = new UserFilters();
        uFilter.AppendEquals(UserColumn.TenDangNhap, userName);
        uFilter.AppendEquals(UserColumn.MatKhau, passWord);
        DataTable dt = DataRepository.UserProvider.GetPaged(uFilter.ToString(), "", 0, int.MaxValue, out ra).ToDataSet(false).Tables[0];
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                return true;
            }
        }
        return false;
    }
    #endregion

    #region GetUserIdByUserName
    protected int GetUserIdByUserName(string userName){
    
        UserFilters uFilter = new UserFilters();
        uFilter.AppendEquals(UserColumn.TenDangNhap, userName);
        DataTable dt = DataRepository.UserProvider.GetPaged(uFilter.ToString(), "", 0, 1, out ra).ToDataSet(false).Tables[0];
        if (dt!=null&&dt.Rows.Count>0)
        {
            return Convert.ToInt32(dt.Rows[0][UserColumn.UserId.ToString()]);
        }
        return 0;
    }
    #endregion

    #region aDK_Click
    protected void aDK_Click(object sender, EventArgs e)
    {
        hddCheckUser.Value = "1";
        dvFormDk.Style.Add("display","block");
        aDK.Visible = false;
    }
    #endregion

}